import PoolItem from "./PoolItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PrefabPool {
    private static _poolMap: Map<cc.Prefab, cc.Node[]> = new Map();
    private static _gids: Map<cc.Prefab, number> = new Map();

    public static create(prefab: cc.Prefab, data?: any): cc.Node {
        let pool = this._poolMap.get(prefab);
        if (pool && pool.length > 0) {
            let node = pool.pop();
            let poolItem = node.getComponent(PoolItem);
            poolItem.reuse();
            if (data) {
                poolItem.init(data);
            }
            return node;
        }
        
        if (!pool) {
            pool = [];
            this._poolMap.set(prefab, pool);
            this._gids.set(prefab, 0);
        }
        
        const node = cc.instantiate(prefab);
        const poolItem = node.getComponent(PoolItem);
        const gid = this._gids.get(prefab) as number;
        poolItem.registPool(pool, gid + 1);
        this._gids.set(prefab, gid + 1);
        console.log("PrefabPool create ", prefab.name, gid + 1);
        if (data) {
            poolItem.init(data);
        }
        return node;
    }
}
